package com.jsy.common.leetcode;

/**
 * 给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出 和为目标值 target  的那 两个 整数，并返回它们的数组下标。
 */
public class ListNodeSum {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        ListNode listNode = addTwoNumbers(l1, l2);
        System.out.println(listNode);
    }

    /**
     * Definition for singly-linked list.
     */

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode l3 = l1;
        ListNode l4 = l2;
        ListNode current = result;
        boolean add = false;
        while (l3 != null || l4 != null) {
            int value1 = 0;
            int value2 = 0;
            if (l3 != null){
                value1=l3.val;
            }
            if (l4 != null){
                value2=l4.val;
            }
            int sum = value1 + value2 + current.val;
            if (sum > 9) {
                current.val = sum - 10;
                add = true;
            } else {
                current.val = sum;
            }
            if (l3 != null) {
                l3 = l3.next;
            }
            if (l4 != null) {
                l4 = l4.next;
            }
            if (add) {
                current.next = new ListNode(1);
            } else {
                if (l3 != null || l4 != null){
                    current.next = new ListNode(0);
                }
            }
            current = current.next;
            add = false;
        }
        return result;
    }

}
